<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="charge-off-detail">
    <div class="charge-info">
      <ChargeOffDetailTop :write-off-detail="writeOffDetail" :show-mobile-page="showMobilePage" @updateDetail="updateDetail"/>
      <div class="table-list">
        <div class="flex-center" style="margin-bottom:10px;">
          <div>
            <Title :title="'核销记录'" :is-show="true" :total="writeOffDetail.total" />
          </div>
          <DataDisplay v-if="!showMobilePage" :data-list="statisticsList" style="flex:1"/>
        </div>
        <DataDisplay v-if="showMobilePage" :data-list="statisticsList" style="flex:1;margin-bottom: 8px;"/>
        <el-table
          v-loading="listLoading"
          v-if="writeOffDetail.items.length > 0"
          :data="writeOffDetail.items"
          element-loading-text="加载中..."
          header-cell-class-name="order-data-header-cell"
          empty-text="暂无数据"
          class="fb-table"
          fit
          hightlight-current-row
        >
          <el-table-column align="left" label="订单编号" min-width="220">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.orderId" placement="top">
                <div class="overflow link" @click="goOrder(scope.row)">
                  {{ scope.row.orderId || '--' }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="left" label="下单日期" min-width="110">
            <template slot-scope="scope">{{ scope.row.orderTime | standardFormatNoHour }}</template>
          </el-table-column>
          <el-table-column align="left" label="品牌名称" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.theme" />
            </template>
          </el-table-column>
          <el-table-column align="right" label="含税金额(元)" min-width="140">
            <template slot-scope="scope"><PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" /></template>
          </el-table-column>
          <el-table-column align="right" label="核销金额(元)" min-width="140">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.entryAmount" :price="scope.row.entryAmount / 100" />
              <span v-if="scope.row.isLoseEfficacy === 1" style="color: #E54C4C">(已重置)</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="收入类型" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.incomeTypeStr">{{ scope.row.incomeTypeStr || '--' }}</span>
              <span v-else-if="scope.row.incomeTypeStr === 0">{{ scope.row.incomeTypeStr }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="账号" min-width="130">
            <template slot-scope="scope">
              <div v-if="scope.row.resourceName">
                <resource-info
                  v-if="scope.row.category === 0"
                  :resource-name="scope.row.resourceName"
                  :account-name-organization="scope.row.accountNameOrganization"
                  :resource-id="scope.row.resourceCode"
                  account-name-platform="none"
                  account-belong-name="none"
                />
                <ToolTip v-else :content="scope.row.resourceName" />
              </div>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="下单平台" min-width="120">
            <template slot-scope="scope">
              <el-row type="flex">
                <platformIcon :data="scope.row.orderPlatform" :key="scope.row.id" />
                <ToolTip :content="scope.row.orderPlatform" />
              </el-row>
            </template>
          </el-table-column>
          <el-table-column align="left" label="客户名称" min-width="150">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.clientName" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="客户类型" min-width="90">
            <template slot-scope="scope">
              <span v-if="scope.row.category === 1">
                {{ scope.row.clientType | clientType }}
              </span>
              <span v-else>
                {{ scope.row.clientType | clientStatusFilter }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="封账状态" min-width="90">
            <template slot-scope="scope">
              <div style="display:flex;align-items:center">
                <div :style="scope.row.sealBillType === 1?{backgroundColor: '#31CC9C'}:{backgroundColor: '#FD8546'}" class="dot"/>
                <div>{{ scope.row.sealBillType | setSealBillType }}</div>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column align="left" label="审批状态" min-width="90">
            <template slot-scope="scope">{{ scope.row.reviewState | setReviewState }}</template>
          </el-table-column> -->
          <el-table-column align="left" label="撤销核销" fixed="right">
            <template slot-scope="scope">
              <el-button
                :disabled="scope.row.sealBillType !== 0|| (scope.row.category === 1 && scope.row.projectStatus > 1) || (scope.row.category === 0 && scope.row.orderType === 2) "
                type="text"
                size="small"
                class="to-cancel"
                @click="toCancel(scope)"
              >撤销核销</el-button>
            </template>
          </el-table-column>
        </el-table>
        <EmptyPlaceholder v-else style="margin:20px 0 32px;" />
      </div>
      <el-row type="flex" justify="end" class="pagination-area">
        <el-pagination
          v-show="writeOffDetail.total > 0"
          :current-page="writeOffDetail.page"
          :page-size="writeOffDetail.perPage"
          :total="writeOffDetail.total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <InvoiceTable :table-data="writeOffDetail.invoiceList"/>
      <div>
        <Title :title="'操作记录'" font-size="16px" style="margin-bottom:10px;"/>
        <log-time-line :logs="operateLogs" :edit-api="editLogRemark" :class="{'mobile-log-time-line': showMobilePage}" is-fold @success="editRemarkSuccess" />
      </div>
      <detailButton :detail-info="writeOffDetail.orderList" :day-account-id="flowId" @toBack="toBack" />
    </div>
  </div>
</template>
<script>
import platformIcon from '@/components/Common/platformIcon';
import ResourceInfo from '@/components/ResourceInfo';
import detailButton from '@/components/Finance/chargeOffDetailButton';
import LogTimeLine from '@/components/Common/logTimeLine';
import ChargeOffDetailTop from '@/components/Finance/chargeOffDetailTop';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import InvoiceTable from '@/components/Finance/invoiceTable';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import Title from '@/components/Title';
import '@/styles/extend.scss';
import { clientStatusFilter, setSealBillType, setReviewState, setPayWay, clientType, setOperationType } from '@/filters/status';
import { standardFormatNoHour, standardFormat } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { showString } from '@/filters/showString';
import { getWriteOffDetail, cancelWriteOff, getOperation, editLogRemark } from '@/api/finance';
import icon_35 from '@/assets/dataDisplay/icon_35.png';
import icon_36 from '@/assets/dataDisplay/icon_36.png';
import { mapState } from 'vuex';

export default {
  filters: {
    showString,
    clientStatusFilter,
    setSealBillType,
    setReviewState,
    standardFormatNoHour,
    standardFormat,
    setPayWay,
    moneyFilter,
    clientType
  },
  components: { Title, ResourceInfo, detailButton, EmptyPlaceholder, platformIcon,
    ChargeOffDetailTop, LogTimeLine, InvoiceTable, DataDisplay },
  data() {
    return {
      writeOffDetail: {
        items: [],
        orderList: {},
        page: 1,
        perPage: 15,
        total: 0
      },
      flowId: '',
      listLoading: true,
      operateLogs: [],
      incomeAmount: '',
      writeOffAmount: '',
      statisticsList: [
        { data: 0, label: '订单总金额', tooltip: '核销记录内订单的含税金额合计', icon: icon_36 },
        { data: 0, label: '核销总金额', tooltip: '核销记录内核销金额合计', icon: icon_35 }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  created() {
    this.flowId = Number(this.$route.params.chargeOffId) || '';
    this.getDetail();
    this.getOperationDetail();
  },
  methods: {
    editLogRemark,
    updateDetail() {
      this.getDetail();
      this.getOperationDetail();
    },
    getDetail(toPage = 1) {
      getWriteOffDetail(toPage, this.writeOffDetail.perPage, this.flowId).then(res => {
        this.writeOffDetail = res.data;
        this.writeOffDetail.orderList.clientType = clientStatusFilter(
          this.writeOffDetail.orderList.clientType
        );
        this.writeOffDetail.orderList.arrivalTime = standardFormatNoHour(
          this.writeOffDetail.orderList.arrivalTime, 'YYYY/MM/DD'
        );
        this.$set(this.statisticsList[0], 'data', res.data.orderAmount / 100);
        this.$set(this.statisticsList[1], 'data', res.data.chargeAmount / 100);
        this.listLoading = false;
      }, result => {
        this.$message.error(result.message);
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    handleCurrentChange(toPage) {
      this.getDetail(toPage);
    },
    getOperationDetail() {
      getOperation(this.flowId).then(res => {
        this.listLoading = false;
        if (res.data) {
          res.data.forEach(i => {
            if (i.operations) {
              i.operations.forEach(j => {
                this.getLogContent(j);
              });
            }
          });
        }
        this.operateLogs = res.data;
      }).catch(e => {
        this.listLoading = false;
        console.error(e);
      });
    },
    toCancel(scope) {
      this.listLoading = true;
      this.$confirm('确定撤销核销？', '', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        this.listLoading = false;
        const params = {
          type: scope.row.category || 0
        };
        cancelWriteOff(scope.row.id, params).then(res => {
          this.listLoading = false;
          if (this.writeOffDetail.items && this.writeOffDetail.items.length > 1) {
            this.getDetail(this.writeOffDetail.page);
          } else if (this.writeOffDetail.items.length === 1) {
            const writeOffDetail = this.writeOffDetail;
            let page = writeOffDetail.total / writeOffDetail.perPage;
            page = Number(page).toFixed(0);
            this.getDetail(page);
          }
          this.getOperationDetail();
        }, result => {
          this.listLoading = false;
        });
      }).catch(() => {
        this.listLoading = false;
        return;
      });
    },
    toBack() {
      // 区分返回跳转为 封账 还是 流水列表 还是 智能核销列表
      const stepId = Number(this.$route.query.stepId);
      // const chargeOffId = Number(this.$route.params.chargeOffId);
      const sealingId = Number(this.$route.query.sealingId);
      // 返回封账报告
      const isReport = this.$route.query.isReport;
      if (this.$route.query.isIntelligent) {
        this.$router.push({ name: 'intelligentList' });
        return true;
      }
      if (isReport) {
        this.$router.push({
          name: 'sealingStepsDetail',
          params: { id: sealingId }
        });
        return true;
      }
      // END
      if (stepId === 1 || stepId === 2) {
        this.$router.push({
          name: 'sealingStepsDetail',
          params: { id: sealingId }
        });
      } else {
        this.$router.push({
          name: 'dayAccount'
        });
      }
    },
    editRemarkSuccess() {
      this.getOperationDetail();
    },
    getLogContent(item) {
      const type = item.operationType;
      let ans = '';
      switch (type) {
        case 0:
          ans = `新增了流水单`;
          break;
        case 1:
        case 7:
          ans = `${item.content}`;
          break;
        default:
          ans = `${setOperationType(item.operationType)}，订单号：${item.orderId}，金额：${moneyFilter(item.amount / 100, true, '', true)}${item.noWriteOffAmount ? `，可核销金额：${moneyFilter(item.noWriteOffAmount / 100, true, '', true)}` : ''}`;
          break;
      }
      item.content = ans;
    },
    goOrder(item) {
      let routeUrl = null;
      if (!item.category) { // 订单详情
        routeUrl = this.$router.resolve({
          name: 'orderDetail',
          params: { orderId: item.jumpId || item.id }
        });
      } else if (item.category === 1) { // 项目详情
        routeUrl = this.$router.resolve({
          name: 'projectDetail',
          params: { id: item.jumpId || item.id }
        });
      } else if (item.category === 2) { // 萌力订单
        routeUrl = this.$router.resolve({
          name: 'mengliOrderDetail',
          params: { id: item.jumpId || item.id },
          query: { type: item.mengliOrderTab }
        });
      }
      if (routeUrl) window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.charge-off-detail {
  padding: 16px;
  .link {
    cursor:pointer;
    color: #406EFF;
  }
  .charge-info {
    background:#fff;
    min-height: calc(100vh - 60px);
    padding: 16px 24px 50px;
    .charge-form {
      margin-top: 16px;
      margin-left: 12px !important;
      margin-bottom: 20px;
      .el-col {
        margin-bottom: 10px;
      }
      .form-title-item {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
      }
      .form-icon {
        width: 16px;
        height: 16px;
        margin-right: 4px;
      }
      .form-label {
        display: inline-block;
        font-family:PingFangSC-Regular,PingFang SC;
        font-size: 14px;
        color: #999;
      }
      .form-content {
        font-size: 16px;
        color: #333;
        font-family:PingFangSC-Medium,PingFang SC;
        font-weight:500;
        word-break: break-all;
        min-height: 50px;
        line-height: 1.2;
      }
    }
  }
  .empty-img {
    width: 200px;
  }
  .text-black {
    font-weight: 500;
    color: #333;
  }
  .dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-right: 5px;
  }
  .el-row {
    .table-list {
      margin-bottom: 32px;
      background-color: #fff;
      border-bottom-left-radius: 9px;
      border-bottom-right-radius: 9px;
      .el-table {
        border-radius: 10px;
        .to-cancel {
          color: #515151;
          border: 1px solid #e4e4e4;
          &:hover {
            color: #406EFF;
          }
        }
        .to-cancel.is-disabled {
          color: #e0e0e0;
        }
      }
    }
  }
  .to-back {
    margin: 20px 0 0 0;
    .el-button--info {
      width: 120px;
      border: none;
      background:rgba(239,243,251,1);
      border-radius:4px;
      font-size:16px;
      font-weight:400;
      color:rgba(64,110,255,1);
      line-height:16px;
    }
  }
}
.v-model {
  display: none;
}
.overflow {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
</style>
<style lang="scss" scoped>
.mobile-detail-wrap {
  padding: 0 !important;
  .charge-info {
    padding: 12px;
    border-radius: 5px;
  }
  .pagination-area {
    margin-bottom: 8px;
  }
  .mobile-log-time-line {
    ::v-deep .operating-record {
      .el-timeline-item__wrapper {
        .el-timeline-item__content {
          overflow: auto;
          .ellipsis {
            overflow: unset;
          }
          .detail {
            width: fit-content;
          }
        }
      }
    }
  }
  .invoice-container {
    margin-bottom: 26px;
    ::v-deep .title-head {
      justify-content: space-between;
    }
    ::v-deep .data-item-mobile {
      width: 180px !important;
    }
  }
}
</style>
